package reqUpload;

import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@WebServlet(value = "/reqUpload/demo01")
@MultipartConfig
public class requestUploadDemo01 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Access-Control-Allow-Methods", "POST, GET");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type");
        response.setHeader("Access-Control-Allow-Origin", "*");
        Part files = request.getPart("files");
        String fileName = files.getSubmittedFileName();
        String newFileName = UUID.randomUUID() + fileName.substring(fileName.lastIndexOf("."));
        String uploadPath = request.getServletContext().getRealPath("/reqUploads");
        File file = new File(uploadPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        files.write(uploadPath+"/" + newFileName);
        response.setContentType("text/plain; charset=UTF-8");
        response.getWriter().write("{\"msg\":\"文件上传成功\",\"fileName\":\"" +
                                        newFileName+"\",\"code\":200}");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
